import React , { useState,useEffect } from 'react';
import { View, Text } from '@ray-js/ray';
// import styles from '../index.module.less';
import styles from './index.module.less';
import LampTouchSlider from '@ray-js/lamp-vertical-touch-slider';
import { LampRectPickerColor } from '@ray-js/components-ty-lamp';
import OpacitySlider from '@ray-js/lamp-style-slider';

import { putDpData } from '@/utils/sendDp';
import { connectBLEDevice } from '@/utils/ble';
import { dpCodes, globalConfig } from '@/config';

import { getLaunchOptionsSync } from '@ray-js/ray';
import { getDpsInfos, getLaunchOptionsSync } from '@ray-js/ray';

import {
  showToast,
  onDpDataChange,
  offDpDataChange,
  deleteTemporaryPassword,
  createTemporaryPassword,
  updateTempPassword,
} from '@ray-js/ray';

// 光圈坐标一直往左偏移，可能是由样式布局、
// 组件属性设置或者颜色转换函数的问题导致的。下面从多个方面给出排查和修复的方法。

// npm install @ray-js/lamp-vertical-touch-slider --legacy-peer-deps
// npm install @ray-js/components-ty-lamp --legacy-peer-deps
// npm install @ray-js/lamp-style-slider --legacy-peer-deps

const {mode1_color,mode2_color,mode3_color  } = dpCodes;

// 模式一 下的三种光组件
// const ModeOneWhiteLight = ({ value1, setValue1 }) => {
// const ModeOneWhiteLight = React.memo(() => {
//   const handleTouchEnd = (newValue) => {
//     // 打印当前值
//     console.log('LampTouchSlider1 当前值为:', newValue); 
//     setValue1(newValue);
//     putDpData(mode1_color, `ModeOneWhiteLight:${newValue}`); // 发送开关状态到设备
//   };

//   return (
//     <View className={styles.modeContent}>
//       {/* <Text>模式一 - 白光 内容</Text> */}
//       <LampTouchSlider 
//       step={1}
//       className={styles.lampTouchSlider}
//       value={value1} onTouchEnd={handleTouchEnd} 
//       // barColor='linear-gradient(270deg, #7f66ef -14.11%, #c64343 100%) '
//       barColor='#b0a8f9'
//       width='80px' 
//       height='250px' 
//       radius='10px'
//       trackColor='#fff'
//       />
//        {/* barColor = linear-gradient(270deg, #7f66ef -14.11%, #c64343 100%) */}
//     </View>
//   );
// });

const ModeOneWhiteLight = ({ dpValue }) => {
  const [value1, setValue1] = useState(50);

  const [whiteValue, setWhiteValue] = useState<number>(0);

  const handleTouchEnd = (newValue) => {
    // 打印当前值
    console.log('LampTouchSlider1 当前值为:', newValue); 
    setValue1(newValue);
    putDpData(mode1_color, `ModeOneWhiteLight:${newValue}`); //
  };

  useEffect(() => {
    if (dpValue) {
      const match = dpValue.match(/ModeOneWhiteLight:(\d+)/);
      if (match) {
        setWhiteValue(parseInt(match[1], 10));
      }
    }
  }, [dpValue]);

  return (
    <View className={styles.modeContent}>
      {/* <Text>模式一 - 白光 内容</Text> */}
      <View className={styles.sliderContainer}> {/* 新增 View 容器 */}
        <LampTouchSlider 
          step={1}
          className={styles.lampTouchSlider}
          value={whiteValue} 
          onTouchEnd={handleTouchEnd} 
          // barColor='linear-gradient(270deg, #7f66ef -14.11%, #c64343 100%) '
          barColor='#b0a8f9'
          width='80px' 
          height='250px' 
          radius='10px'
          trackColor='#fff'
          // showText={false}
        />
      </View>
      
       {/* barColor = linear-gradient(270deg, #7f66ef -14.11%, #c64343 100%) */}
    </View>
  );
};


const ModeOneColorLight = ({ dpValue }) => {

  const [hsColor, setHsColor] = React.useState<{ h: number; s: number }>
                                ({ h: 0, s: 1000 });      
  const [closed, setClosed] = React.useState(false);

  // 新增状态用于保存当前 RGB 颜色
  const [currentRgb, setCurrentRgb] = React.useState<string>('rgb(0, 0, 0)');

  // 固定色盘宽高
  const RECT_WIDTH = 300;
  const RECT_HEIGHT = 200;

  // HSL 转 RGB 函数，假设亮度 L 为 50%
  // const hslToRgb = (h: number, s: number, l: number): [number, number, number] => {
  //   // 将输入值转换到标准范围
  //   h /= 360;
  //   s /= 1000;
  //   l /= 100;

  //   let r: number, g: number, b: number;

  //   if (s === 0) {
  //     r = g = b = l; // 灰度
  //   } else {
  //     const hue2rgb = (p: number, q: number, t: number): number => {
  //       if (t < 0) t += 1;
  //       if (t > 1) t -= 1;
  //       if (t < 1 / 6) return p + (q - p) * 6 * t;
  //       if (t < 1 / 2) return q;
  //       if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
  //       return p;
  //     };

  //     const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  //     const p = 2 * l - q;
  //     r = hue2rgb(p, q, h + 1 / 3);
  //     g = hue2rgb(p, q, h);
  //     b = hue2rgb(p, q, h - 1 / 3);
  //   }

  //   return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
  // };

   // 修正 HSL 转 RGB 函数
  //  const hslToRgb = (h: number, s: number, l: number): [number, number, number] => {
  //   // 确保 h 在 0 - 360 范围，s 在 0 - 100 范围，l 在 0 - 100 范围
  //   h = ((h % 360) + 360) % 360;
  //   s = Math.max(0, Math.min(100, s / 10)); // 将 s 从 0 - 1000 转换为 0 - 100
  //   l = Math.max(0, Math.min(100, l));

  //   const hNorm = h / 360;
  //   const sNorm = s / 100;
  //   const lNorm = l / 100;

  //   let r: number, g: number, b: number;

  //   if (sNorm === 0) {
  //     r = g = b = lNorm;
  //   } else {
  //     const hue2rgb = (p: number, q: number, t: number): number => {
  //       if (t < 0) t += 1;
  //       if (t > 1) t -= 1;
  //       if (t < 1 / 6) return p + (q - p) * 6 * t;
  //       if (t < 1 / 2) return q;
  //       if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
  //       return p;
  //     };

  //     const q = lNorm < 0.5 ? lNorm * (1 + sNorm) : lNorm + sNorm - lNorm * sNorm;
  //     const p = 2 * lNorm - q;
  //     r = hue2rgb(p, q, hNorm + 1 / 3);
  //     g = hue2rgb(p, q, hNorm);
  //     b = hue2rgb(p, q, hNorm - 1 / 3);
  //   }

  //   return [
  //     Math.round(Math.max(0, Math.min(255, r * 255))),
  //     Math.round(Math.max(0, Math.min(255, g * 255))),
  //     Math.round(Math.max(0, Math.min(255, b * 255)))
  //   ];
  // };
  // 修正 HSL 转 RGB 函数
  const hslToRgb = (h: number, s: number, l: number): [number, number, number] => {
    console.log('hslToRgb 输入:', h, s, l);
    h = ((h % 360) + 360) % 360;
    s = Math.max(0, Math.min(100, s / 10));
    l = Math.max(0, Math.min(100, l));

    const hNorm = h / 360;
    const sNorm = s / 100;
    const lNorm = l / 100;

    let r: number, g: number, b: number;

    if (sNorm === 0) {
      r = g = b = lNorm;
    } else {
      const hue2rgb = (p: number, q: number, t: number): number => {
        if (t < 0) t += 1;
        if (t > 1) t -= 1;
        if (t < 1 / 6) return p + (q - p) * 6 * t;
        if (t < 1 / 2) return q;
        if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
        return p;
      };

      const q = lNorm < 0.5 ? lNorm * (1 + sNorm) : lNorm + sNorm - lNorm * sNorm;
      const p = 2 * lNorm - q;
      r = hue2rgb(p, q, hNorm + 1 / 3);
      g = hue2rgb(p, q, hNorm);
      b = hue2rgb(p, q, hNorm - 1 / 3);
    }

    const result: [number, number, number] = [
      Math.round(Math.max(0, Math.min(255, r * 255))),
      Math.round(Math.max(0, Math.min(255, g * 255))),
      Math.round(Math.max(0, Math.min(255, b * 255)))
    ];
    console.log('hslToRgb 输出:', result);
    return result;
  };

  // const handleTouchStart = (e: any) => {
  //   console.log(e, 'handleTouchStart');
  // };

  // const handleTouchMove = (e: any) => {
  //   console.log(e, 'handleTouchMove');
  //   if (e.h !== undefined && e.s !== undefined) {
  //     setHsColor({ h: e.h, s: e.s }); 
  //     const [r, g, b] = hslToRgb(e.h, e.s, 50); // 假设亮度为 50%
  //     console.log(`当前坐标对应的 RGB 颜色: RGB(${r}, ${g}, ${b})`);
  //     setCurrentRgb(`rgb(${r}, ${g}, ${b})`);
  //   }
  // };

  // const handleTouchEnd = (e: any) => {
  //   console.log(e, 'handleTouchEnd');
  //   if (e.h !== undefined && e.s !== undefined) {
  //     setHsColor({ h: e.h, s: e.s }); 
  //     const [r, g, b] = hslToRgb(e.h, e.s, 50); // 假设亮度为 50%
  //     console.log(`当前坐标对应的 RGB 颜色: RGB(${r}, ${g}, ${b})`);
  //     setCurrentRgb(`rgb(${r}, ${g}, ${b})`);
  //     // putDpData(mode1_color, `ModeOneColorLight:(${r}, ${g}, ${b})`); // 发送开关状态到设备
  //     putDpData(mode1_color, `ModeOneColorLight:(${currentRgb}),lightstrenghth:(${value})`);
  //   }
  // };

  const handleTouchStart = (e: any) => {
    console.log(e, 'handleTouchStart');
    handleCoordinateEvent(e);
  };

  const handleTouchMove = (e: any) => {
    console.log(e, 'handleTouchMove');
    handleCoordinateEvent(e);
  };

  const handleTouchEnd = (e: any) => {
    console.log(e, 'handleTouchEnd');
    handleCoordinateEvent(e);
  };

  const handleCoordinateEvent = (e: any) => {
    if (e.h !== undefined && e.s !== undefined) {
      // 确保 h 和 s 在合理范围内
      const newH = Math.max(0, Math.min(360, e.h));
      const newS = Math.max(0, Math.min(1000, e.s));
      setHsColor({ h: newH, s: newS });

      const [r, g, b] = hslToRgb(newH, newS, 50);
      console.log(`当前坐标对应的 RGB 颜色: RGB(${r}, ${g}, ${b})`);
      const newRgb = `rgb(${r}, ${g}, ${b})`;
      setCurrentRgb(newRgb);
      putDpData(mode1_color, `ModeOneColorLight:(${newRgb}),lightstrenghth:(${value})`);
    } else if (e.x !== undefined && e.y !== undefined) {
      // 根据坐标计算 h 和 s 值
      // x 坐标对应色相 h，范围 0 - 360
      const h = Math.min(360, Math.max(0, (e.x / RECT_WIDTH) * 360));
      // y 坐标对应饱和度 s，范围 0 - 1000
      const s = Math.min(1000, Math.max(0, ((RECT_HEIGHT - e.y) / RECT_HEIGHT) * 1000));

      setHsColor({ h, s });
      const [r, g, b] = hslToRgb(h, s, 50);
      console.log(`当前坐标对应的 RGB 颜色: RGB(${r}, ${g}, ${b})`);
      const newRgb = `rgb(${r}, ${g}, ${b})`;
      setCurrentRgb(newRgb);
      putDpData(mode1_color, `ModeOneColorLight:(${newRgb}),lightstrenghth:(${value})`);
    }
  };

  // 彩光亮度条
  const [value, setValue] = useState(100);

  const handleMove = v => {
    console.log('move====', v);
    setValue(v); // 更新亮度值
    putDpData(mode1_color, `ModeOneColorLight:(${currentRgb}),lightstrenghth:(${v})`);
  };

    // RGB 转 HSL 函数
    // const rgbToHsl = (r: number, g: number, b: number): [number, number, number] => {
    //   r /= 255;
    //   g /= 255;
    //   b /= 255;
  
    //   const max = Math.max(r, g, b);
    //   const min = Math.min(r, g, b);
    //   let h = 0;
    //   let s = 0;
    //   const l = (max + min) / 2;
  
    //   if (max === min) {
    //     h = s = 0; // 灰度
    //   } else {
    //     const d = max - min;
    //     s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  
    //     switch (max) {
    //       case r:
    //         h = (g - b) / d + (g < b ? 6 : 0);
    //         break;
    //       case g:
    //         h = (b - r) / d + 2;
    //         break;
    //       case b:
    //         h = (r - g) / d + 4;
    //         break;
    //     }
  
    //     h = Math.round((h / 6) * 360);
    //     s = Math.round(s * 1000);
    //   }
  
    //   return [h, s, Math.round(l * 100)];
    // };



    const rgbToHsl = (r: number, g: number, b: number): [number, number, number] => {
      const rNorm = r / 255;
      const gNorm = g / 255;
      const bNorm = b / 255;
  
      const max = Math.max(rNorm, gNorm, bNorm);
      const min = Math.min(rNorm, gNorm, bNorm);
      let h = 0;
      let s = 0;
      const l = (max + min) / 2;
  
      if (max !== min) {
        const d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  
        switch (max) {
          case rNorm:
            h = (gNorm - bNorm) / d + (gNorm < bNorm ? 6 : 0);
            break;
          case gNorm:
            h = (bNorm - rNorm) / d + 2;
            break;
          case bNorm:
            h = (rNorm - gNorm) / d + 4;
            break;
        }
  
        h = (h / 6) * 360;
      }
  
      // 将 s 从 0 - 1 转换为 0 - 1000
    // 定义微调参数
    const hueOffset = 0; // 色相偏移量，可按需调整
    const saturationFactor = 1; // 饱和度系数，可按需调整
    const lightnessOffset = 0.8; // 亮度偏移量，可按需调整

    // 应用微调
    const adjustedH = ((h + hueOffset) % 360 + 360) % 360;
    const adjustedS = Math.max(0, Math.min(1000, s * 1000 * saturationFactor));
    const adjustedL = Math.max(0, Math.min(100, l * 100 + lightnessOffset));

    return [
      Math.round(adjustedH),
      Math.round(adjustedS),
      Math.round(adjustedL)
    ];
  };
  

  useEffect(() => {
    
    if (dpValue) {
      console.log('ModeOneColorLight dpValue:', dpValue);
      const match = dpValue.match(/ModeOneColorLight:\((rgb\(\d+, \d+, \d+\))\),lightstrenghth:\((\d+)\)/);
      if (match) {
        setCurrentRgb(match[1]);
        console.log('currentRgb:', match[1]);
        // setValue(parseInt(match[2]));
        // console.log('value:', match[2]);
        const brightnessValue = parseInt(match[2], 10);
        setValue(brightnessValue);
        console.log('value:', brightnessValue);

        // 提取 RGB 数值
        const rgbMatch = match[1].match(/rgb\((\d+), (\d+), (\d+)\)/);
        if (rgbMatch) {
          const r = parseInt(rgbMatch[1], 10);
          const g = parseInt(rgbMatch[2], 10);
          const b = parseInt(rgbMatch[3], 10);
          const [h, s] = rgbToHsl(r, g, b);
          setHsColor({ h, s });
        }
      }
    }
  }, [dpValue]);


    // 注册监听器
    // useEffect(() => {
    //   const dpDataChangeHandler = ({ dps }) => {
    //     // 遍历每个变化的 DP 点
    //     Object.entries(dps).forEach(([dpCode, dpValue]) => {
    //       handleDpDataChange({ dpCode, dpValue });
    //     });
    //   };
  
    //   onDpDataChange(dpDataChangeHandler);
  
    //   // 清理函数，组件卸载时执行
    //   return () => {
    //     offDpDataChange(dpDataChangeHandler);
    //   };
    // }, []);
  
  // 定义 DP 数据变化处理函数
  const handleDpDataChange = ({ dpCode, dpValue }) => {
    // 根据变化的 DP 点进行不同的处理
    console.log(`DP Code: ${dpCode}, DP Value: ${dpValue}`);

    if (dpCode === '109') {       // 模式1灯光设置
      console.log(`109bjhDP111 Code: ${dpCode}, DP Value: ${dpValue}`);
      // setModeDpValues(prev => ({ ...prev, mode1: dpValue }));

      const match = dpValue.match(/ModeOneColorLight:\((rgb\(\d+, \d+, \d+\))\),lightstrenghth:\((\d+)\)/);
      if (match) {
        setCurrentRgb(match[1]);
        console.log('currentRgb:', match[1]);
        // setValue(parseInt(match[2]));
        // console.log('value:', match[2]);
        const brightnessValue = parseInt(match[2], 10);
        setValue(brightnessValue);
        console.log('value:', brightnessValue);

        // 提取 RGB 数值
        const rgbMatch = match[1].match(/rgb\((\d+), (\d+), (\d+)\)/);
        if (rgbMatch) {
          const r = parseInt(rgbMatch[1], 10);
          const g = parseInt(rgbMatch[2], 10);
          const b = parseInt(rgbMatch[3], 10);
          const [h, s] = rgbToHsl(r, g, b);
          setHsColor({ h, s });
        }
      }
    }
  };

  useEffect(() => {
    const { deviceId } = getLaunchOptionsSync().query || {};
    if (deviceId) {
      // 获取设备所有 DP 信息
      getDpsInfos({
        devId: deviceId,
        gwId: deviceId
      })
      .then((res) => {
        console.log('获取到的所有 DP 信息:', res);
        res.forEach((item) => {
          const { dpId, value } = item;
          // 处理布尔类型的字符串值，转换为布尔值
          let processedValue = value;
          if (typeof value === 'string' && (value === 'true' || value === 'false')) {
            processedValue = value === 'true';
          }
          // 将 dpId 转换为字符串
          const dpCodeStr = String(dpId);
          // console.log(`DP Code: ${code}, DP Value: ${processedValue}`);
          handleDpDataChange({ dpCode: dpCodeStr, dpValue: processedValue });
        });
      })
      .catch((error) => {
        console.error('获取 DP 信息失败:', error);
      });
    } else {
      console.error('无法获取设备 ID');
    }
  }, []);


  Render({
    // 其他xxx
    renderChannel() {
      const eventChannelName = 'lampRectPickerColorEventChannel';
      this.instance.eventChannel.on(eventChannelName, e => {
        // 此处可以接收到当颜色变化时传递的颜色数据
        const {
          rgba, // [r, g , b, a]
          touchType, // : 'start' | 'move' | 'end'
          pos,
        } = e;
        console.log('eventChannel get', e);
        if (rgba) {
          const [r, g, b] = rgba;
          const [h, s] = rgbToHsl(r, g, b);
          setHsColor({ h, s });
          setCurrentRgb(`rgb(${r}, ${g}, ${b})`);
          console.log("eventChannel get",e.pos);
        }
      });
    },
  });

 


  return (
    <View className={styles.modeContent}
          style={{ display: 'flex', flexDirection: 'column' }}> 
      {/* 新增 View 容器，可通过修改样式移动内部组件 */}
      <View style={{ marginTop: '-10%' }}> 
        <LampRectPickerColor
          hs={hsColor}
          borderRadius={16}
          borderRadiusStyle="16rpx 16rpx 16rpx 16rpx"
          // rectWidth={344}
          // rectHeight={200}
          rectWidth={RECT_WIDTH}
          rectHeight={RECT_HEIGHT}
          thumbRadius={12}
          closed={closed}
          isShowColorTip
          onTouchStart={handleTouchStart}
          onTouchMove={handleTouchMove}
          onTouchEnd={handleTouchEnd}
        />
      </View>

      <View style={{ marginTop: '3%' }}> 
        <Text style={{ fontSize: '18px', color: 'black' , marginLeft: '3%'}}>
        当前亮度: {value}%</Text>
          <View style={{ marginTop: '3%' }}> 
            <OpacitySlider
                style={{
                  paddingLeft: 16,
                }}
                // label="亮度"
                valueStyle={{ color: 'blue' }}
                min={0}
                max={100}
                disable={false}
                value={value}
                onTouchMove={handleMove}
                // trackBackgroundColor="linear-gradient(270deg, #000000 2.57%, rgba(255, 255, 255, 0) 100%)"
                // trackBackgroundColor="linear-gradient(270deg, rgba(255, 255, 255, 0) 2.57%, #000000 100%)"
                trackBackgroundColor={`linear-gradient(270deg, rgba(255, 255, 255, 0) 2.57%, ${currentRgb} 100%)`}
                thumbColorFormatterConfig={{
                  formatter: 'hsl(0deg 0% value%)',
                  // scale: 0.1,
                  scale: 1,
                }}
              />
            </View>
      </View>


    </View>
  );
};



const ModeOneGradientLight = () => (
  <View className={styles.modeContent}>
    <Text>模式一 - 七彩渐变 内容</Text>
  </View>
);

const ModeTwoWhiteLight = () => {
  const [value1, setValue1] = useState(50);

  const handleTouchEnd = (newValue) => {
    // 打印当前值
    console.log('LampTouchSlider2 当前值为:', newValue); 
    setValue1(newValue);
    putDpData(mode2_color, `ModeTwoWhiteLight:${newValue}`); //
  };

  return (
    <View className={styles.modeContent}>
      {/* <Text>模式一 - 白光 内容</Text> */}
      <View className={styles.sliderContainer}> {/* 新增 View 容器 */}
        <LampTouchSlider 
          step={1}
          className={styles.lampTouchSlider}
          value={value1} 
          onTouchEnd={handleTouchEnd} 
          // barColor='linear-gradient(270deg, #7f66ef -14.11%, #c64343 100%) '
          barColor='#b0a8f9'
          width='80px' 
          height='250px' 
          radius='10px'
          trackColor='#fff'
          // showText={false}
        />
      </View>
      
       {/* barColor = linear-gradient(270deg, #7f66ef -14.11%, #c64343 100%) */}
    </View>
  );
};

const ModeTwoColorLight = () => {

  const [hsColor, setHsColor] = React.useState<{ h: number; s: number }>({ h: 0, s: 1000 });
  const [closed, setClosed] = React.useState(false);
    // 新增状态用于保存当前 RGB 颜色

    const [currentRgb, setCurrentRgb] = React.useState<string>('rgb(0, 0, 0)');
  
  const handleEnd = (e: { h: number; s: number }) => {
    setHsColor(e);
  };

  // HSL 转 RGB 函数，假设亮度 L 为 50%
  const hslToRgb = (h: number, s: number, l: number): [number, number, number] => {
    // 将输入值转换到标准范围
    h /= 360;
    s /= 1000;
    l /= 100;

    let r: number, g: number, b: number;

    if (s === 0) {
      r = g = b = l; // 灰度
    } else {
      const hue2rgb = (p: number, q: number, t: number): number => {
        if (t < 0) t += 1;
        if (t > 1) t -= 1;
        if (t < 1 / 6) return p + (q - p) * 6 * t;
        if (t < 1 / 2) return q;
        if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
        return p;
      };

      const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
      const p = 2 * l - q;
      r = hue2rgb(p, q, h + 1 / 3);
      g = hue2rgb(p, q, h);
      b = hue2rgb(p, q, h - 1 / 3);
    }

    return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
  };

  const handleTouchStart = (e: any) => {
    console.log(e, 'handleTouchStart');
  };

  const handleTouchMove = (e: any) => {
    console.log(e, 'handleTouchMove');
    if (e.h !== undefined && e.s !== undefined) {
      // 更新 hsColor 状态
      setHsColor({ h: e.h, s: e.s }); 
      const [r, g, b] = hslToRgb(e.h, e.s, 50); // 假设亮度为 50%
      console.log(`当前坐标对应的 RGB 颜色: RGB(${r}, ${g}, ${b})`);
      setCurrentRgb(`rgb(${r}, ${g}, ${b})`);
    }
  };

  const handleTouchEnd = (e: any) => {
    console.log(e, 'handleTouchEnd');
    if (e.h !== undefined && e.s !== undefined) {
      // 更新 hsColor 状态
      setHsColor({ h: e.h, s: e.s }); 
      const [r, g, b] = hslToRgb(e.h, e.s, 50); // 假设亮度为 50%
      console.log(`当前坐标对应的 RGB 颜色: RGB(${r}, ${g}, ${b})`);
      setCurrentRgb(`rgb(${r}, ${g}, ${b})`);
      // putDpData(mode2_color, `ModeTwoColorLight:(${r}, ${g}, ${b})`); // 发送开关状态到设备
      putDpData(mode2_color, `ModeTwoColorLight:(${currentRgb}),lightstrenghth:(${value})`);
    }
  };
  // 彩光亮度条
  const [value, setValue] = useState(100);
  const handleMove = v => {
    console.log('move====', v);
    setValue(v);
    putDpData(mode2_color, `ModeTwoColorLight:(${currentRgb}),lightstrenghth:(${value})`);
  };


  return (
    <View className={styles.modeContent}
          style={{ display: 'flex', flexDirection: 'column' }}> 
      {/* 新增 View 容器，可通过修改样式移动内部组件 */}
      <View style={{ marginTop: '-10%' }}> 
        <LampRectPickerColor
          hs={hsColor}
          borderRadius={16}
          borderRadiusStyle="16rpx 16rpx 16rpx 16rpx"
          rectWidth={344}
          rectHeight={200}
          thumbRadius={12}
          closed={closed}
          isShowColorTip
          onTouchStart={handleTouchStart}
          onTouchMove={handleTouchMove}
          onTouchEnd={handleTouchEnd}
        />
      </View>

      <View style={{ marginTop: '3%' }}> 
        <Text style={{ fontSize: '18px', color: 'black' , marginLeft: '3%'}}>
        当前亮度: {value}%</Text>
          <View style={{ marginTop: '3%' }}> 
            <OpacitySlider
                style={{
                  paddingLeft: 16,
                }}
                // label="亮度"
                valueStyle={{ color: 'blue' }}
                min={0}
                max={100}
                disable={false}
                value={value}
                onTouchMove={handleMove}
                // trackBackgroundColor="linear-gradient(270deg, #000000 2.57%, rgba(255, 255, 255, 0) 100%)"
                trackBackgroundColor={`linear-gradient(270deg, rgba(255, 255, 255, 0) 2.57%, ${currentRgb} 100%)`}
                thumbColorFormatterConfig={{
                  formatter: 'hsl(0deg 0% value%)',
                  // scale: 0.1,
                  scale: 1,
                }}
              />
            </View>
      </View>
    </View>
  );
};


const ModeTwoGradientLight = () => (
  <View className={styles.modeContent}>
    <Text>模式二 - 七彩渐变 内容</Text>
  </View>
);


const ModeThreeWhiteLight = () => {
  const [value1, setValue1] = useState(50);
  
  const handleTouchEnd = (newValue) => {
    // 打印当前值
    console.log('LampTouchSlider3 当前值为:', newValue); 
    setValue1(newValue);
    putDpData(mode3_color, `ModeThreeWhiteLight:${newValue}`); //
  };

  return (
    <View className={styles.modeContent}>
      {/* <Text>模式一 - 白光 内容</Text> */}
      <LampTouchSlider 
      step={1}
      className={styles.lampTouchSlider}
      value={value1} onTouchEnd={handleTouchEnd} 
      // barColor='linear-gradient(270deg, #7f66ef -14.11%, #c64343 100%) '
      barColor='#b0a8f9'
      width='80px' 
      height='250px' 
      radius='10px'
      trackColor='#fff'

      />
      
       {/* barColor = linear-gradient(270deg, #7f66ef -14.11%, #c64343 100%) */}
    </View>
  );
};



const ModeThreeColorLight = () => {

  const [hsColor, setHsColor] = React.useState<{ h: number; s: number }>({ h: 0, s: 1000 });
  const [closed, setClosed] = React.useState(false);

  // 新增状态用于保存当前 RGB 颜色
  const [currentRgb, setCurrentRgb] = React.useState<string>('rgb(0, 0, 0)');
  
  const handleEnd = (e: { h: number; s: number }) => {
    setHsColor(e);
  };

  const hslToRgb = (h: number, s: number, l: number): [number, number, number] => {
    // 将输入值转换到标准范围
    h /= 360;
    s /= 1000;
    l /= 100;

    let r: number, g: number, b: number;

    if (s === 0) {
      r = g = b = l; // 灰度
    } else {
      const hue2rgb = (p: number, q: number, t: number): number => {
        if (t < 0) t += 1;
        if (t > 1) t -= 1;
        if (t < 1 / 6) return p + (q - p) * 6 * t;
        if (t < 1 / 2) return q;
        if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
        return p;
      };

      const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
      const p = 2 * l - q;
      r = hue2rgb(p, q, h + 1 / 3);
      g = hue2rgb(p, q, h);
      b = hue2rgb(p, q, h - 1 / 3);
    }

    return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
  };

  const handleTouchStart = (e: any) => {
    console.log(e, 'handleTouchStart');
  };

  const handleTouchMove = (e: any) => {
    console.log(e, 'handleTouchMove');
    if (e.h !== undefined && e.s !== undefined) {
      // 更新 hsColor 状态
      setHsColor({ h: e.h, s: e.s }); 
      const [r, g, b] = hslToRgb(e.h, e.s, 50); // 假设亮度为 50%
      console.log(`当前坐标对应的 RGB 颜色: RGB(${r}, ${g}, ${b})`);
      setCurrentRgb(`rgb(${r}, ${g}, ${b})`);
    }
  };

  const handleTouchEnd = (e: any) => {
    console.log(e, 'handleTouchEnd');
    if (e.h !== undefined && e.s !== undefined) {
      // 更新 hsColor 状态
      setHsColor({ h: e.h, s: e.s }); 
      const [r, g, b] = hslToRgb(e.h, e.s, 50); // 假设亮度为 50%
      console.log(`当前坐标对应的 RGB 颜色: RGB(${r}, ${g}, ${b})`);
      setCurrentRgb(`rgb(${r}, ${g}, ${b})`);
      putDpData(mode3_color, `ModeThreeColorLight:(${currentRgb}),lightstrenghth:(${value})`); // 发送开关状态到设备
    }
  };
  // 彩光亮度条
  const [value, setValue] = useState(100);
  const handleMove = v => {
    console.log('move====', v);
    setValue(v);
    putDpData(mode3_color, `ModeThreeColorLight:(${currentRgb}),lightstrenghth:(${value})`); // 发送开关状态到设备
  };


  return (
    <View className={styles.modeContent}
          style={{ display: 'flex', flexDirection: 'column' }}> 
      {/* 新增 View 容器，可通过修改样式移动内部组件 */}
      <View style={{ marginTop: '-10%' }}> 
        <LampRectPickerColor
          hs={hsColor}
          borderRadius={16}
          borderRadiusStyle="16rpx 16rpx 16rpx 16rpx"
          rectWidth={344}
          rectHeight={200}
          thumbRadius={12}
          closed={closed}
          isShowColorTip
          onTouchStart={handleTouchStart}
          onTouchMove={handleTouchMove}
          onTouchEnd={handleTouchEnd}
        />
      </View>

      <View style={{ marginTop: '3%' }}> 
        <Text style={{ fontSize: '18px', color: 'black' , marginLeft: '3%'}}>
        当前亮度: {value}</Text>
          <View style={{ marginTop: '3%' }}> 
            <OpacitySlider
                style={{
                  paddingLeft: 16,
                }}
                // label="亮度"
                valueStyle={{ color: 'blue' }}
                min={0}
                max={100}
                disable={false}
                value={value}
                onTouchMove={handleMove}
                // trackBackgroundColor="linear-gradient(270deg, #000000 2.57%, rgba(255, 255, 255, 0) 100%)"
                // trackBackgroundColor="linear-gradient(270deg, rgba(255, 255, 255, 0) 2.57%, #000000 100%)"
                trackBackgroundColor={`linear-gradient(270deg, rgba(255, 255, 255, 0) 2.57%, ${currentRgb} 100%)`}
                thumbColorFormatterConfig={{
                  formatter: 'hsl(0deg 0% value%)',
                  // scale: 0.1,
                  scale: 1,
                }}
              />
            </View>
      </View>
    </View>
  );
};


const ModeThreeGradientLight = () => (
  <View className={styles.modeContent}>
    <Text>模式三 - 七彩渐变 内容</Text>
  </View>
);

// 模式一 组件
export const ModeOne = ({ activeLightIndex, handleLightTabClick, dpValue }) => {
  // const [value1, setValue1] = useState(82);
  // const lightComponents = [ModeOneWhiteLight, ModeOneColorLight, ModeOneGradientLight];

  const lightComponents = [
    () => <ModeOneWhiteLight dpValue={dpValue} />,
    () => <ModeOneColorLight dpValue={dpValue} />,
    // 假设还有其他组件
    ModeOneGradientLight
  ];

  const lights = [
    { name: '白光' },
    { name: '彩光' },
    { name: '七彩渐变' },
  ];

  return (
    <View key="mode-one-container" className={styles.newContainer_1}>
      <Text style={{
        display: 'flex',
        fontSize: '16px',
        color: '#000',
        marginTop: '5%',
        marginLeft: '-70%'
      }}>模式一
      </Text>

      {/* 光类型切换标签 */}
      <View className={styles.tabContainer}>
        {lights.map((light, index) => (
          <View
            key={index}
            className={`${styles.tabItem} ${index === activeLightIndex ? styles.activeTab : ''}`}
            onClick={() => handleLightTabClick(index)}
          >
            <Text>{light.name}</Text>
          </View>
        ))}
      </View>

      <View className={styles.newContainer_title}>
        {lights.map((_, index) => {
          const offset = (index - activeLightIndex) * 100;
          const LightComponent = lightComponents[index];
          return (
            <View
              key={index}
              className={`${styles.modePage} ${index === activeLightIndex ? styles.showPage : ''}`}
              style={{ transform: `translateX(${offset}%)` }}
            >
              <LightComponent />
            </View>
          );
        })}
      </View>

    </View>
  );
};



// 模式三 组件
export const ModeTwo = ({ activeLightIndex, handleLightTabClick, dpValue }) => {
    const lightComponents = [ModeTwoWhiteLight, ModeTwoColorLight, ModeTwoGradientLight];
    const lights = [
      { name: '白光' },
      { name: '彩光' },
      { name: '七彩渐变' },
    ];
  
    return (
    <View key="mode-two-container" className={styles.newContainer_2}>
        <Text style={{
          display: 'flex',
          fontSize: '16px',
          color: '#000',
          marginTop: '5%',
          marginLeft: '-70%'
        }}>模式二</Text>
  
        {/* 光类型切换标签 */}
        <View className={styles.tabContainer}>
          {lights.map((light, index) => (
            <View
              key={index}
              className={`${styles.tabItem} ${index === activeLightIndex ? styles.activeTab : ''}`}
              onClick={() => handleLightTabClick(index)}
            >
              <Text>{light.name}</Text>
            </View>
          ))}
        </View>
  
        <View className={styles.newContainer_title}>
          {lights.map((_, index) => {
            const offset = (index - activeLightIndex) * 100;
            const LightComponent = lightComponents[index];
            return (
              <View
                key={index}
                className={`${styles.modePage} ${index === activeLightIndex ? styles.showPage : ''}`}
                style={{ transform: `translateX(${offset}%)` }}
              >
                <LightComponent />
              </View>
            );
          })}
        </View>
      </View>
    );
  };

// 模式三 组件
export const ModeThree = ({ activeLightIndex, handleLightTabClick , dpValue}) => {
  const lightComponents = [ModeThreeWhiteLight, ModeThreeColorLight, ModeThreeGradientLight];
  const lights = [
    { name: '白光' },
    { name: '彩光' },
    { name: '七彩渐变' },
  ];

  return (
    <View key="mode-three-container" className={styles.newContainer_3}>
      <Text style={{
        display: 'flex',
        fontSize: '16px',
        color: '#000',
        marginTop: '5%',
        marginLeft: '-70%'
      }}>模式三</Text>

      {/* 光类型切换标签 */}
      <View className={styles.tabContainer}>
        {lights.map((light, index) => (
          <View
            key={index}
            className={`${styles.tabItem} ${index === activeLightIndex ? styles.activeTab : ''}`}
            onClick={() => handleLightTabClick(index)}
          >
            <Text>{light.name}</Text>
          </View>
        ))}
      </View>

      <View className={styles.newContainer_title}>
        {lights.map((_, index) => {
          const offset = (index - activeLightIndex) * 100;
          const LightComponent = lightComponents[index];
          return (
            <View
              key={index}
              className={`${styles.modePage} ${index === activeLightIndex ? styles.showPage : ''}`}
              style={{ transform: `translateX(${offset}%)` }}
            >
              <LightComponent />
            </View>
          );
        })}
      </View>
    </View>
  );
};


// 模式二 组件
// export const ModeTwo = ({ activeLightIndex, handleLightTabClick, hsColor, closed, handleTouchStart, handleTouchMove, handleTouchEnd }) => {
//   const lightComponents = [ModeTwoWhiteLight, ModeTwoColorLight, ModeTwoGradientLight];
//   const lights = [
//     { name: '白光' },
//     { name: '彩光' },
//     { name: '七彩渐变' },
//   ];

//   return (

//     <View key="mode-two-container" className={styles.newContainer_2}>
//         <Text style={{
//           display: 'flex',
//           fontSize: '16px',
//           color: '#000',
//           marginTop: '5%',
//           marginLeft: '-70%'
//         }}
//         >模式二</Text>

//         {/* 光类型切换标签 */}
//         <View className={styles.tabContainer}>
//           {lights.map((light, index) => (
//             <View
//               key={index}
//               className={`${styles.tabItem} ${index === activeLightIndex ? styles.activeTab : ''}`}
//               onClick={() => handleLightTabClick(index)}
//             >
//               <Text>{light.name}</Text>
//             </View>
//           ))}
//         </View>

//         <View className={styles.newContainer_title}>
//           {lights.map((_, index) => {
//             const offset = (index - activeLightIndex) * 100;
//             const LightComponent = lightComponents[index];
//             return (
//               <View
//                 key={index}
//                 className={`${styles.modePage} ${index === activeLightIndex ? styles.showPage : ''}`}
//                 style={{ transform: `translateX(${offset}%)` }}
//               >
//                 <LightComponent />
//               </View>
//             );
//           })}
//         </View>
//     </View>

//   );
// };


// 模式一 下的三种光组件
// const ModeOneWhiteLight = ({ value1, setValue1 }) => (
//   <View className={styles.modeContent}>
//     {/* <Text>模式一 - 白光 内容</Text> */}
    
//     <LampTouchSlider value={value1} onTouchEnd={setValue1} />
//   </View>
// );